﻿using System;
using System.Linq;

using Crevice2D.Core.Data;
using Crevice2D.Core.Extension;
using Crevice2D.Core.Managers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Patyk.Core;

namespace Patyk.Data
{
    public class Terrain : StaticObject
    {
        public Color[,] Sprite { get; protected set; }
        public Matrix Transformation
        {
            get
            {
                return Matrix.Identity * Matrix.CreateTranslation(new Vector3(Position, 0.0f));
            }
        }

        private Map _map;

        public Terrain(Map map)
        {
            _map = map;
            LoadContent();
        }

        public override bool LoadContent()
        {
            CreateForeground();
            return base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            RenderManager.SpriteBatch.Draw(_texture, new Rectangle(0, 0, RenderManager.ScreenWidth, RenderManager.ScreenHeight), Color.White);
            base.Draw(gameTime);
        }

        private void CreateForeground()
        {
            var colors = new Color[_map.MapWidth * _map.MapHeight];
            for (int x = 0; x < _map.MapWidth; ++x)
            {
                for (int y = 0; y < _map.MapHeight; ++y)
                {
                    if (_map.MapTexture[x,y] == 0)
                        colors[x + y * RenderManager.ScreenWidth] = Color.Transparent;
                    else
                        colors[x + y * RenderManager.ScreenWidth] = Color.Black;
                }
            }

            _texture = new Texture2D(RenderManager.Device, RenderManager.ScreenWidth, RenderManager.ScreenHeight, false, SurfaceFormat.Color);
            _texture.SetData(colors);
            Sprite = _texture.To2DArray();
        }
    }
}